import 'package:flutter/material.dart';
import 'package:sharing/model/book.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sharing/utils/whole_apis.dart';
import 'package:sharing/net/ris_read_apis.dart';
import 'package:sharing/net/net_util.dart';
import 'package:sharing/ui/widget/book_info.dart';
import 'package:sharing/model/book_list.dart';
import 'package:sharing/ui/my/create_book_list.dart';

// 用户自己的书单, 包括用开的和非公开的
class OwnBookInfosWidget extends StatefulWidget {
  OwnBookInfosWidget({Key key}) : super(key: key);

  @override
  _OwnBookInfosWidgetState createState() => _OwnBookInfosWidgetState();
}

class _OwnBookInfosWidgetState extends State<OwnBookInfosWidget> {
  List<Book> _books = [];
  int bik =0;

  // 书单推荐
  List<BookList> _book_lists = [];

  void _loadBookLists() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String authorization = await prefs.getString("authorization");
    NetUtil.originGet(
        WholeApis.hostName + RisReadApis.ownBookList,
        Options(
          headers: {
            "authorization": authorization,
          },
        ), (Response response) {
      print("response ${response.data}");
      var code = response.data["code"];
      var message = response.data["message"];
      if (code == 200 && message != null) {
        _book_lists.clear();
        _book_lists = BookList.fromJson(message);
        print("bookList $_book_lists");
      }
    });
  }

  // 加载图书信息
  void _loadBookInfos() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String authorization = await prefs.getString("authorization");
    NetUtil.originGet(WholeApis.hostName + RisReadApis.ownBookInfos,
        Options(headers: {"authorization": authorization}),
        (Response response) {
      print("data ${response.data}");
      var code = response.data["code"];
      var message = response.data["message"];
      if (code == 200 && message != null) {
        _books.clear();
        _books = Book.fromJson(message);
        setState(() {});
      }
    });
  }

  Widget _booksInfosItem(BuildContext context, int index) {
    return _bookItem(_books[index]);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 异步加载图书
    _loadBookInfos();

    // 加载书单的消息
    _loadBookLists();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Scaffold(
        appBar: AppBar(
          title: Text("原创"),
          elevation: 0.0,
        ),
        body: ListView.builder(
          itemBuilder: _booksInfosItem,
          itemCount: _books.length,
        ),
      ),
    );
  }

  // _bookItem
  Widget _bookItem(Book book) {
    return GestureDetector(
      child: Container(
        // color: Colors.black38,
        margin: const EdgeInsets.symmetric(horizontal: 4.0, vertical: 4),
        child: Card(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              Container(
                height: 72,
                width: 72,
                padding: const EdgeInsets.all(4.0),
                child: Image.network(
                  WholeApis.hostName + "/" + book.cover,
                  fit: BoxFit.cover,
                ),
              ),
              Expanded(
                child: Container(
                  alignment: Alignment.topLeft,
                  padding: const EdgeInsets.all(4.0),
                  child: Column(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Container(
                        child: Text(book.name),
                      ),
                      Container(
                        child: Text("介绍" +
                            (book.introduction == null
                                ? "无"
                                : book.introduction)),
                      ),
                      Container(
                        child:
                            Text(book.copyRight == null ? "无" : book.copyRight),
                      ),
                      Container(
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              child: Text(book.dateTime == null
                                  ? "无"
                                  : book.dateTime.toString()),
                            ),
                            Container(
                              child: Text(
                                  book.publish != null && book.publish == false
                                      ? "个人"
                                      : "公开"),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      onTap: () {
        // 点击查看图书的详情
        Navigator.of(context).push(MaterialPageRoute(builder: (context) {
          return BookInfo(
            book: book,
          );
        }));
      },
      onLongPress: () {
        print("长按事件");
        // 赋值id
        bik = book.id;
        showModalBottomSheet(context: context, builder: _btm);

      },
    );
  }

  Widget _btm(BuildContext context) {
    return Container(
      height: 308,
      width: double.infinity,
      //  color:Colors.red,
      child: ListView.builder(
        itemBuilder: _buildBottomItem,
        itemCount: _book_lists.length + 2,
      ),
    );
  }

  Widget _buildBottomItem(BuildContext context, int index) {
    if (index == 0) {
      return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.symmetric(horizontal: 32, vertical: 4.0),
        child: Text(
          "请添加到...",
          style: TextStyle(
            fontSize: 20,
            color: Colors.black,
          ),
        ),
      );
    }

    if (index == _book_lists.length + 1) {
      return GestureDetector(
        child: Container(
          height: 48,
          alignment: Alignment.center,
          padding: EdgeInsets.symmetric(horizontal: 32, vertical: 4.0),
          child: Text(
            "新建书单",
            style: TextStyle(fontSize: 20),
          ),
        ),
        onTap: () {
          print("新建书单");
          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
            return CreateBookListPage();
          }));
        },
      );
    }
    return GestureDetector(
      child: Container(
        height: 48,
        margin: EdgeInsets.only(bottom: 4.0),
        color: Colors.white,
        alignment: Alignment.center,
        child: Row(
          children: <Widget>[
            Expanded(
              child: Container(
                alignment: Alignment.center,
                child: Text(
                  _book_lists[index - 1].name,
                  style: TextStyle(fontSize: 16),
                ),
              ),
            ),
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 16),
              child: Text(_book_lists[index-1].publish !=null &&_book_lists[index -1].publish == true ? "公开":"个人",style: TextStyle(fontSize: 10,color:Colors.black45),),
            ),
          ],
        ),
      ),

      onTap: ()async{
       await  _push2Booklist(_book_lists[index-1].id, bik);
       Navigator.of(context).pop();
      },
    );
  }

  void _push2Booklist(int bkid, int bid) async{
    print("bkid $bkid bid $bid");

    SharedPreferences prefs = await SharedPreferences.getInstance();
    String authorization = await prefs.getString("authorization");
    NetUtil.originPost(WholeApis.hostName+RisReadApis.add2BookList, Options(headers: {"authorization":authorization},data: {
      "book_list_id":bkid,
      "book_info_id":bid,
    }), (Response response){
      // todo
      print("response data ${response.data}");
    });
  }
}
